package com.jiuwu.spring.eshop.controller;

import com.jiuwu.spring.eshop.db.entity.Manager;
import com.jiuwu.spring.eshop.respository.ManagerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Optional;

@Controller
@RequestMapping(value = "/manage")
public class ManageControl {

    @Autowired
    ManagerRepository managerRepository;


    @RequestMapping("/login")
    public String loginReq(){
        return "/manage/Login_M";
    }

    @RequestMapping("/loginCheck")
    public String loginCheck(@RequestParam(value="name", required=true) String userName,
                             @RequestParam(value="password", required=true) String password){
        Optional<Manager> optional = managerRepository.findById(userName);
        if(optional.isPresent()){
            Manager sqlManager = optional.get();
            if(sqlManager.getPassword().equals(password)){

                HttpSession session = getSession();
                session.setAttribute("userName", userName);

                return "/manage/index";
            }
        }
        return "/manage/Login_M";
    }

    @RequestMapping("/index")
    public String index(){
        return "/manage/index";
    }

    private HttpSession getSession(){
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attrs.getRequest();
        return request.getSession();
    }

 //------------------------------------thymeleaf------------------------------

    @PostMapping("/admin/login")
    public String thymeleafLogin(@RequestParam("name") String username,
                                 @RequestParam("password") String password,
                                 HttpSession session, Model model){
        Optional<Manager> optional = managerRepository.findById(username);
        if(optional.isPresent()) {
            Manager sqlManager = optional.get();
            if (sqlManager.getPassword().equals(password)) {
                session.setAttribute("loginUser",username);
                return "redirect:/manage/admin.html";
            }else {
                model.addAttribute("msg","密码错误，重新登录");
                return "index";
            }
        }else {
            model.addAttribute("msg","用户名错误");
            return "index";
        }

    }
}
